#include <string.h>
#include <signal.h>
#include <panel-applet.h>
#include <gtk/gtklabel.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <string.h>

#define REFRESH_RATE 30

GtkLabel *label;

void my_update_applet() {
  // callback na pravidelne obnovovanie textu appletu
  // zistime uplnu cestu skriptu ~/.gnomepipeapplet/script.sh
  char *home = getenv("HOME");
  char *script = (char *)malloc(sizeof(char)*1000);
  strcpy(script,home);
  strcat(script,"/.gnomepipeapplet/script.sh");
  //printf("%s\n",script);
  // zistime ci ten skript existuje
  struct stat statinfo;
  int i = stat(script, &statinfo);
  //printf("%d\n",i);
  // ak skript existuje, spustime ho a preberieme vystup
  int n = 1000;
  char * buffer = (char*)malloc(sizeof(char)*n+1);
  if (i==0) {
    FILE *f = popen(script,"r");
    getline(&buffer,&n,f);
	  pclose(f);
    printf("nacital som %s\n",buffer);
    // nastavime text labelu
    gtk_label_set_text(label,buffer);
  } else {
    // ak skript neexistuje, vypiseho cestu k skriptu, snad sa user dovtipi ze mu ten skript chyba
    gtk_label_set_text(label,"~/.gnomepipeapplet/script.sh");
  }
  //free(home);
  free(script);
  free(buffer);
  // znovu spusti refresh za stanoveny cas
  alarm(REFRESH_RATE);
}

static gboolean
myexample_applet_fill (PanelApplet *applet, const gchar *iid, gpointer data)
{
  if (strcmp (iid, "OAFIID:PipeApplet") != 0)
    return FALSE;

  label = (GtkLabel*)gtk_label_new ("???");
  gtk_container_add (GTK_CONTAINER (applet), (GtkWidget*)label);
  gtk_widget_show_all (GTK_WIDGET (applet));

  signal(SIGALRM,my_update_applet);
  my_update_applet();

  return TRUE;
}

PANEL_APPLET_BONOBO_FACTORY ("OAFIID:ExampleApplet_Factory",
                             PANEL_TYPE_APPLET,
                             "The Hello World Applet",
                             "0",
                             myexample_applet_fill,
                             NULL);
